package com.example.springboottemplate.Utiles.RedisCache;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.example.springboottemplate.Utiles.RedisData.RedisData;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
@RequiredArgsConstructor
public class RedisCacheClient {
    private final StringRedisTemplate stringRedisTemplate;
    // 线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    // <缓存注入>
    public void setRedisCacheOrigin(String key, Object value, Long time, TimeUnit unit) {
        /*
         * 1.调用Redis工具类操作Redis,实现缓存注入
         * 2.存入Redis数据必须转换为String
         * */
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    /*
     * <缓存击穿>
     * 设置逻辑过期属性，以及写入Redis
     * */
    public void setRedisCachePreHeating(String key, Object value, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData(value, LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData), time, unit);
    }

    /*
     * <缓存穿透>
     * */
    public <T, LongID> T cachePassThrough(String keyPrefix, LongID id, Class<T> tClass, Function<LongID, T> fallBack, Long time, TimeUnit unit) {
        String resultKey = keyPrefix + id;
        // 先查询缓存
        String cacheData = stringRedisTemplate.opsForValue().get(resultKey);
        // 1.判断是否为空
        if (cacheData != null && !cacheData.equals("")) {
            // 转换为T类型 并直接返回
            return JSONUtil.toBean(cacheData, tClass);
        }
        // 再次判断命中的是否是空值""
        if (Objects.equals(cacheData, "")) {
            return null;
        }
        // 2.如果为空
        // 2.1 先去Mysql中查询 如果查询到了 就存入缓存区中 最后返回
        T queryWithMysqlByIdResult = fallBack.apply(id);
        if (queryWithMysqlByIdResult != null) {
            // 写入Redis中去 调用我们的缓存注入的方法
            this.setRedisCacheOrigin(resultKey, queryWithMysqlByIdResult, time, unit);
            return queryWithMysqlByIdResult;
        }
        // 2.2 如果为空 并设置好过期时间 返回一个null值
        stringRedisTemplate.opsForValue().set(resultKey, JSONUtil.toJsonStr(""), time, unit);
        return null;
    }

    /*
     * 缓存击穿
     * */
    public <T, LongID> T cacheBreakDownByLogicalExpiration(String keyPrefix, LongID id, Class<T> tClass, Function<LongID, T> fallback, Long time, TimeUnit unit) {
        String resultKey = keyPrefix + id;
        String jsonData = stringRedisTemplate.opsForValue().get(resultKey);
        if (StrUtil.isBlank(jsonData)) {
            // 如果命中缓存是空
            return null;
        }
        // 不为空，命中Redis，先将JsonData反序列化成java对象
        RedisData redisData = JSONUtil.toBean(jsonData, RedisData.class);
        // 先获取到我们的Data数据
        Object data = redisData.getData();
        T redisCacheResultData = JSONUtil.toBean((String) data, tClass);
        // 再获取到我们的过期时间
        LocalDateTime expireTime = redisData.getExpire();
        // 没有过期就返回命中数据
        if (expireTime.isAfter(LocalDateTime.now())) {
            return redisCacheResultData;
        }
        // 如果过期，需要重新进行缓存重建
        // 缓存重建
        // 获取互斥锁
        String lockKey = "cache:lock:" + id;
        // 如果获取锁成功
        if (redisCacheTryLock(lockKey)) {
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    // 查询数据库
                    T redisCacheToMysqlResultData = fallback.apply(id);
                    // 缓存重建 写入redis
                    this.setRedisCachePreHeating(resultKey, redisCacheToMysqlResultData, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    redisCacheUnLock(lockKey);
                }
            });
        }
        // 如果失败就直接返回旧的数据
        return redisCacheResultData;
    }

    /*
     *  缓存互斥锁
     * */
    public Boolean redisCacheTryLock(String key) {
        // Value 为 1就是表示该key数据不存在返回1
        return stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10L, TimeUnit.SECONDS);
    }

    /*
     * 释放互斥锁
     * */
    public void redisCacheUnLock(String key) {
        stringRedisTemplate.delete(key);
    }
}
